package com.selenium.core.functionlibrary;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

/**
 * Parses HTML table and returns required data
 *  
 * @author bhadauria
 *
 */
public class HTMLTableParser {

	/**
	 * Returns page DOM
	 * @param html
	 * @return page DOM
	 */
	public static Document getDocument(String html) {
		return Jsoup.parse(html);
	}

	/**
	 * Counts number of rows in a table  
	 * 
	 * @param html
	 * @param tableLocator
	 * @return Number of rows in a table
	 */
	public static Integer countRows(String html, String tableLocator) {
		return getDocument(html).select(tableLocator).first().getElementsByTag(
				"tr").size();
	}

	/**
	 * Returns number of columns in a row
	 * 
	 * @param html
	 * @param tableLocator
	 * @return
	 */
	public static Map<Integer, Integer> countColumnsInRow(String html,
			String tableLocator) {

		Map<Integer, Integer> tableMap = new HashMap<Integer, Integer>();

		Integer tableRows = 0;
		Elements rowElements = getDocument(html).select(tableLocator).first()
				.getElementsByTag("tr");

		for (Iterator<Element> rowIterator = rowElements.iterator(); rowIterator
				.hasNext();) {
			tableRows++;
			tableMap.put(tableRows, rowIterator.next().getElementsByTag("td")
					.size());
		}
		return tableMap;
	}
	
	/**
	 * Returns data from HTML table
	 * 
	 * @param html
	 * @param tableLocator
	 * @return <code>Map</code> of row count and corresponding table data
	 */
	public static Map<Integer, String> getTableData(String html, String tableLocator) {
		
		Map<Integer, String> tableData = new HashMap<Integer, String>();
		Elements rowElement = getDocument(html).getElementsByTag("tr");
		Integer rowCount = 0;
		
		for (Iterator<Element> rowIterator = rowElement.iterator(); rowIterator.hasNext();) {						
			rowCount++;
			tableData.put(rowCount, rowIterator.next().getElementsByTag("td").text()); 			
		}		
		return tableData;
	}
}
